<?php
namespace app\common\behavior;

use think\Db;
use think\helper\Time;

class WriteLog
{
    public function run(&$params)
    {
        if(config('base.write_log')==true){
            $request = request();
            $action = $request->action();
            if($request->isPost()){
                $noAllow = ['mainstats','gettodo'];
                if(!in_array($action,$noAllow)){
                    switch ($request->module()){
                        case 'home':
                            $utype = 'member';
                            break;
                        default:
                            $utype = str_decode(cookie('utype'));
                            break;
                    }
                    $uid = is_login($utype);
                    $username='';
                    if($uid>0){
                        $username = Db::table('user')->where('uid',$uid)->value('username');
                    }
                    if(!empty($request->post())){
                        $data = json_encode($request->param());
                    }
                    $logsData=[
                        'utype'=>$utype,
                        'uid'=>$uid,
                        'username'=>$username,
                        'module'=>$request->module(),
                        'controller'=>$request->controller(),
                        'action'=>$request->action(),
                        'url'=>$request->url(),
                        'data'=>$data,
                        'ip'=>$request->ip(),
                        'create_time'=>time()
                    ];
                    $logs = cache('logs_data');
                    $logs[]=$logsData;
                    if(count($logs)>=120){
                        debug('begin');
                        cache('logs_data',null);
                        //只保留3天内数据
                        $time30Day = Time::daysAgo('3');
                        Db::table('action_log')->where('create_time', '<', $time30Day)->delete();
                        Db::table('action_log')->insertAll($logs);
                        debug('end');
                        trace(debug('begin','end').'s','debug');
                    }else{
                        cache('logs_data',$logs);
                    }
                }
            }
        }else{
            cache('logs_data',null); //清除缓存
        }
    }
}